package com.alimama.mail;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alimama.utils.SmsUtils;

public class MailSend {

	private static final Logger logger = LoggerFactory.getLogger(MailSend.class);

	// 发件人邮箱地址 huijun.jinag@qq.com
	private static final String SENDERS_MAILBOX_ADDRESS = "jhj831143@163.com";
	// 邮件标题
	private static final String EmailTitle = "test";
	// 邮箱开通的stmp服务后得到的客户端授权码 jgefyvzwqrfhdffb
	private static final String EMAIL_AUTHORIZATION_CODE = "jhj831143";

	/**
	 * 邮件发送功能
	 * 
	 * @param RecipientsMailboxAddress
	 *            收件人邮箱地址
	 * @return fals true 发送成功 false 发送失败
	 */
	public static boolean QQEmail(String RecipientsMailboxAddress) {
		boolean fals = false;
		Properties properties = new Properties();
		properties.put("mail.transport.protocol", "smtp");// 连接协议
		properties.put("mail.smtp.host", "smtp.163.com");// 主机名
		properties.put("mail.smtp.port", 465);// 端口号
		properties.put("mail.smtp.auth", "true");
		properties.put("mail.smtp.ssl.enable", "true");// 设置是否使用ssl安全连接 ---一般都使用
		properties.put("mail.debug", "true");// 设置是否显示debug信息 true 会在控制台显示相关信息
		try {
			// 得到回话对象
			Session session = Session.getInstance(properties);
			// 获取邮件对象
			Message message = new MimeMessage(session);
			// 设置发件人邮箱地址
			message.setFrom(new InternetAddress(SENDERS_MAILBOX_ADDRESS));
			// 设置收件人邮箱地址
			// 设置多个收件人
			/*
			 * message.setRecipients(Message.RecipientType.TO, new
			 * InternetAddress[] { new InternetAddress("1225609736@qq.com"), new
			 * InternetAddress("1304010353@qq.com"), new
			 * InternetAddress("1668284913@qq.com") });
			 */
			message.setRecipient(Message.RecipientType.TO, new InternetAddress(RecipientsMailboxAddress));// 一个收件人
			// 设置邮件标题
			message.setSubject(EmailTitle);
			// 设置邮件内容 内容为六位数验证码
			message.setText(SmsUtils.getSmsCode());
			// 得到邮差对象
			Transport transport = session.getTransport(); // 连接自己的邮箱账户
			// 密码为QQ邮箱开通的stmp服务后得到的客户端授权码
			transport.connect(SENDERS_MAILBOX_ADDRESS, EMAIL_AUTHORIZATION_CODE);
			// 发送邮件
			transport.sendMessage(message, message.getAllRecipients());
			transport.close();
			fals = true;
		} catch (AddressException ae) {
			logger.error(ae.getMessage());
		} catch (MessagingException me) {
			logger.error(me.getMessage());
		}
		return fals;
	}

	public static void main(String[] args) {
		System.out.println(QQEmail("huijun.jiang@qq.com"));
	}

}
